package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 目标:
 *
 * @author YUE
 * @date 2024/6/11 9:36
 */
@Aspect
@Component
public class AutoFillAspect {

    /*
      通过切入点指定我们需要拦截的类 或 方法
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFilePointCut(){}

    /*
        前置通知
     */
    @Before("autoFilePointCut()")
    public void autoFile(JoinPoint joinPoint) {
        System.out.println("前置通知开始执行...");

        // 为实体类公共属性设置值
        MethodSignature signature =(MethodSignature) joinPoint.getSignature(); // 获得方法签名对象
        // 获得当前被拦截的对象
        Method method = signature.getMethod();
        //获得当前方法上的注解对象
        AutoFill annotation = method.getAnnotation(AutoFill.class);

        // 获取当前数据库操作类型
        OperationType operationType = annotation.type();

        // 获取实体类
        Object[] args = joinPoint.getArgs(); // 获取当前被拦截方法上的参数列表
        if (args == null || args.length == 0){
            return;
        }
        Object entity = args[0];

        // 赋值内容
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        if(operationType == OperationType.INSERT){
            try {
                Method setCreateTimeMethod = entity.getClass().getDeclaredMethod("setCreateTime",LocalDateTime.class);
                setCreateTimeMethod.invoke(entity,now);
                Method setUpdateTimeMethod = entity.getClass().getDeclaredMethod("setUpdateTime",LocalDateTime.class);
                setUpdateTimeMethod.invoke(entity,now);
                Method setCreateUserMethod = entity.getClass().getDeclaredMethod("setCreateUser",Long.class);
                setCreateUserMethod.invoke(entity,currentId);
                Method setUpdateUserMethod = entity.getClass().getDeclaredMethod("setUpdateUser",Long.class);
                setUpdateUserMethod.invoke(entity,currentId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            try {
                Method setUpdateTimeMethod = entity.getClass().getDeclaredMethod("setUpdateTime",LocalDateTime.class);
                setUpdateTimeMethod.invoke(entity,now);
                Method setUpdateUserMethod = entity.getClass().getDeclaredMethod("setUpdateUser",Long.class);
                setUpdateUserMethod.invoke(entity,currentId);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
